<template>
  <div class="main-container" style="background-color: #F7FAFD;">
    <div class="header-wrapper">
      <h2 class="top">
        <van-icon class="back-icon" name="arrow-left" size="30px" @click="goBack" />
        <span class="title-text">用药查询</span>
      </h2>
    </div>
    <div class="search-container">
      <div class="search-bar">
        <div class="search-box">
          <input type="text" placeholder="搜索疾病/药品名称" v-model="searchQuery" @input="handleInput" />
          <i class="el-icon-search" @click="handleSearch"></i>
        </div>
      </div>
      <button @click="clearSearch" class="cancel-button" style="margin-top: -4px;margin-right: -18px;">取消</button>
      <ul v-if="shouldShowResults" class="result-list">
        <li v-for="(item, index) in filteredItems" :key="index" class="result-item" :style="getItemStyle(item)" @click="handleItemClick(item)">
          <span v-for="(part, partIndex) in getHighlightedParts(item)" :key="partIndex" :style="part.style">
            {{ part.text }}
          </span>
        </li>
      </ul>
    </div>
    <div class="article-list-container">
      <div v-for="article in articles" :key="article.id" class="article-item" @click="goToDetails(article)">
        <div class="article-content-wrapper">
          <div class="article-title">
            <span class="article-title-text">{{ article.drugName }} ({{ getAliasDisplay(article.alias) }})</span>
          </div>
          <div class="article-text">
            <p class="ellipsis-text">
              {{ getDisplayContent(article.drugFactory) }}
            </p>
          </div>
        </div>
        <div class="article-image">
          <div class="article-image-block">
            <img src="https://tse1-mm.cn.bing.net/th/id/OIP-C.YhdOuoXmIUGUBSRSDLGXrwHaHa?rs=1&pid=ImgDetMain" alt="文章图片" />
          </div>
        </div>
      </div>
    </div>
    <van-loading size="24px" style="margin-left: 150px">加载中...</van-loading>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [],
      shouldShowResults: false,
      articles: [],
      maxChars: 29
    };
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => item.includes(this.searchQuery));
    }
  },
  methods: {
    goBack(){
      this.$router.go(-1);
    },
    handleSearch() {
      if (this.searchQuery) {
        this.axios.get(`http://localhost:10086/api/doctor/drug_info/SearchDrugInfo/${this.searchQuery}`).then(res => {
          if (res.data.data.length === 0) {
            this.articles = [];
          } else {
            this.articles = res.data.data;
          }
          this.shouldShowResults = false;
        });
      }
    },
    handleInput() {
      if (this.searchQuery) {
        this.shouldShowResults = this.filteredItems.length > 0;
      } else {
        this.shouldShowResults = false;
      }
    },
    clearSearch() {
      this.searchQuery = '';
      this.shouldShowResults = false;
      this.findDrugInfoList();
    },
    findDrugInfoList() {
      this.axios.get('http://localhost:10086/api/doctor/drug_info/findDrugInfoList').then(res => {
        this.articles = res.data.data;
        this.items = this.articles.map(article => article.drugName);
      }).catch(err => {
        console.log(err);
      });
    },
    goToDetails(article) {
      this.$router.push({
        name: 'drugInfo',
        params: { id: article.id }
      });
    },
    getDisplayContent(content) {
      if (content.length > this.maxChars) {
        return content.slice(0, this.maxChars) + '...';
      }
      return content;
    },
    getAliasDisplay(alias) {
      if (alias.length > 5) {
        return alias.slice(0, 5) + '...';
      }
      return alias;
    },
    getHighlightedParts(item) {
      const parts = [];
      let startIndex = 0;
      let matchIndex = item.indexOf(this.searchQuery, startIndex);
      while (matchIndex!== -1) {
        if (matchIndex > startIndex) {
          parts.push({ text: item.slice(startIndex, matchIndex), style: { color: 'gray' } });
        }
        parts.push({ text: item.slice(matchIndex, matchIndex + this.searchQuery.length), style: { color: 'blue' } });
        startIndex = matchIndex + this.searchQuery.length;
        matchIndex = item.indexOf(this.searchQuery, startIndex);
      }
      if (startIndex < item.length) {
        parts.push({ text: item.slice(startIndex), style: { color: 'gray' } });
      }
      return parts;
    },
    getItemStyle(item) {
      if (item.includes(this.searchQuery)) {
        return { cursor: 'pointer' };
      }
      return {};
    },
    handleItemClick(item) {
      this.searchQuery = item;
      this.handleSearch();
    }
  },
  watch: {
    searchQuery(newValue) {
      if (!newValue) {
        this.findDrugInfoList();
      }
    }
  },
  created() {
    const token = JSON.parse(localStorage.getItem("token"));
    if (!token) {
      this.$message.error('请先登录');
      setTimeout(() => {
        this.$router.push({ name: 'login' });
      }, 666);
    }
    this.axios.defaults.headers.common['token'] = token;
    this.findDrugInfoList();
  }
};
</script>

<style scoped>
.main-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header-wrapper {
  background-color: white;
}

.top {
  display: flex;
  align-items: center;
  height: 50px;
  position: relative;
}

.back-icon {
  position: absolute;
  left: 10px;
}

.title-text {
  width: 100%;
  text-align: center;
}

.search-container {
  width: 400px;
  margin: 50px 20px;
}

.search-bar {
  width: 280px;
  float: left;
  margin-left: 30px;
  align-items: center;
  border-radius: 4px;
  overflow: hidden;
}

.search-box {
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 25px;
  padding: 8px 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 90%;
  margin: 0;
  flex: 1;
}

.search-input {
  flex: 1;
  padding: 8px;
  border: none;
  outline: none;
}

.cancel-button {
  background: none;
  border: none;
  padding: 16px 21px;
  color: #007AFF;
  cursor: pointer;
}

.result-list {
  margin-left: 30px;
  list-style: none;
  padding: 0;
  margin-top: 10px;
}

.result-item {
  padding: 8px;
  border-bottom: 1px solid #ccc;
}

.result-item:last-child {
  border-bottom: none;
}

.article-list-container {
  width: 80%;
  margin: 0 auto;
}

.article-item {
  display: flex;
  align-items: center;
  margin: 20px 0;
  padding: 20px;
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 15px;
  box-sizing: border-box;
}

.article-content-wrapper {
  flex: 1;
}

.article-title {
  margin-bottom: 5px;
  word-break: break-word;
}

.article-title-text {
  font-weight: 700;
  font-size: 17px;
}

.article-text {
  overflow: hidden;
}

.article-text p {
  font-size: 12px;
  color: gray;
}

.ellipsis-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.article-image {
  width: 100px;
  height: 80px;
  margin-left: 20px;
}

.article-image-block {
  width: 100%;
  height: 100%;
}

img {
  width: 100%;
  height: 100%;
}
</style>